# -*- coding: utf-8 -*-
# File : fisco_test.py
# Author: taoyahui
# Date : 2021/7/18
import requests
from django.http import HttpResponse
import results
import json
from HelloWorld.models import Contract

headers = {'Content-Type': 'application/json'}
hello_world_abi = [{"constant": False, "inputs": [{"name": "n", "type": "string"}], "name": "set", "outputs": [],
                    "payable": False, "stateMutability": "nonpayable", "type": "function"},
                   {"constant": True, "inputs": [], "name": "get",
                    "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view",
                    "type": "function"}, {"inputs": [],
                                          "payable": False, "stateMutability": "nonpayable", "type": "constructor"}]


def list_contract(request):
    """
    分页的形式列出所有合约
    :return:
    """
    page = request.GET.get('page')

    res = requests.post(url="http://localhost:5002/WeBASE-Front/contract/contractList", headers=headers, json={
        "groupId": "1",
        "pageNumber": page,
        "pageSize": 10,
        "contractName": "",
        "contractAddress": "",
        "contractStatus": 2
    })
    if res.status_code != 200:
        return HttpResponse(json.dumps(results.system_error_result, ensure_ascii=False))
    res_get_json = json.loads(res.text)
    print(res_get_json)
    contract_list = []
    for data in res_get_json['data']:
        contract = {
            '合约名称':data['contractName'],
            '合约地址': data['contractAddress'],
            '部署时间': data['deployTime'],
            '创建时间': data['createTime'],
            '修改时间': data['modifyTime'],
            'abi':data['contractAbi']
        }
        contract_list.append(contract)
    return HttpResponse(json.dumps({
        'code': 200,
        'data':contract_list
    }))


def helloworld_set(request):
    value = request.GET.get("value")
    contract_list = Contract.objects.filter(name="HelloWorld")
    if len(contract_list) == 0:
        return HttpResponse(json.dumps(results.system_error_result))
    contract = contract_list[0]
    contract_address = contract.address
    hello_world_abi = json.loads(contract.abi)
    print(hello_world_abi)
    headers = {'Content-Type': 'application/json'}
    data = {
        "groupId": "1",
        "user": "0x95fe2373661c37413b7af32b82244b3b4955905c",
        "contractName": "HelloWorld",
        "contractPath": "test",
        "funcName": "set",
        "funcParam": [value],
        "contractAddress": contract_address,
        "contractAbi": hello_world_abi,
        "cnsName": ""
    }
    print(json.dumps(data))
    # print("*" * 50)
    # print("{\"groupId\":\"1\",\"user\":\"0x95fe2373661c37413b7af32b82244b3b4955905c\",\"contractName\":\"HelloWorld\",\"contractPath\":\"test\",\"version\":\"\",\"funcName\":\"set\",\"funcParam\":[\"hahahah\"],\"contractAddress\":\"0x4d4f514b5caa3841826f614ea19a56aa2e512cea\",\"contractAbi\":[{\"constant\":false,\"inputs\":[{\"name\":\"n\",\"type\":\"string\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\",\"funcId\":0}],\"useAes\":false,\"useCns\":false,\"cnsName\":\"\"}")
    res = requests.post(url="http://localhost:5002/WeBASE-Front/trans/handle", headers=headers, data=json.dumps(data))
    return HttpResponse(json.dumps({
        'code':200,
        'data':res.text
    }))


def helloworld_get(request):
    contract_list = Contract.objects.filter(name="HelloWorld")
    if len(contract_list) == 0:
        return HttpResponse(json.dumps(results.system_error_result))
    contract = contract_list[0]
    contract_address = contract.address
    hello_world_abi = json.loads(contract.abi)
    data = {"groupId": "1",
            "user": "",
            "contractName": "HelloWorld",
            "contractPath": "test",
            "version": "",
            "funcName": "get",
            "funcParam": [],
            "contractAddress": contract_address,
            "contractAbi": hello_world_abi,
            "useAes": False,
            "useCns": False,
            "cnsName": ""
            }
    res = requests.post(url="http://localhost:5002/WeBASE-Front/trans/handle", headers=headers, data=json.dumps(data).replace("\\",""))
    return HttpResponse(json.dumps({
        'code':200,
        'data':res.text
    }))
